﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OBUCare.Core.Models;

namespace OBUCare.Core.BL
{
    /// <summary>
    /// 管理权限相关的类
    /// </summary>
    public class AccessRightsMgr
    {
        /// <summary>
        /// 保存用户能访问的所有权限列表
        /// </summary>
        IEnumerable<Operator_FunctionInfo> accessFunctions;

        public AccessRightsMgr(OPERATOR o)
        {
            this.Operator = o;
            using (UserMgr uMgr = new UserMgr())
            {
                this.accessFunctions = uMgr.GetOperatorFunctions(o.OPERATOR_NO).ToList();
            }
        }

        /// <summary>
        /// 当前用户
        /// </summary>
        public OPERATOR Operator
        {
            get;
            private set;
        }

        /// <summary>
        /// 检查用户是否对被检测的URL有权限，有则返回true
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public bool CheckAccessRight(string url)
        {
            if (this.accessFunctions == null)
                return false;
            else
            {
                var temp = accessFunctions.FirstOrDefault(f => IsMatch(f.MODULE_URI, url));
                return temp != null;
            }
        }


        private bool IsMatch(string urlSource, string urlTarget)
        {
            return urlSource.Equals(urlTarget, StringComparison.InvariantCultureIgnoreCase);
        }

        public string GetDefaultPage()
        {
            string defUrl = "/RepairOrders/NewOrder";
            if (this.CheckAccessRight(defUrl))
                return defUrl;
            else if (this.accessFunctions.Count() == 0)
            {
                return "";
            }
            else
            {
                var allSubItems = (from i in this.accessFunctions
                                   where i.MODULE_LEVEL > 0
                                   orderby i.MODULE_LEVEL, i.MODULE_INDEX
                                   select i).OrderBy(i => i.ID);

                if (allSubItems.Count() > 0)
                    return allSubItems.First().MODULE_URI;
                else
                {
                    return this.accessFunctions.OrderBy(i => i.MODULE_LEVEL).OrderBy(i => i.MODULE_INDEX).First().MODULE_URI;

                }
            }
        }
    }
}
